#include <Arduino.h>
#include <Servo.h>
#include <Wire.h> //Arduino内置IIC
#include <ESP8266WiFi.h> 
#include "screen.h"
#include "wifi.h"
#include "server.h"
#include "fetchinfo.h"
#include "state.h"
#include "serial.h"
#include <ESPAsyncWebServer.h>
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>BUTTON
#define BUTTON_PIN 2
#define BUTTON_PIN_2 15
bool Button_Pressed = false;
const unsigned long DebounceDelay = 50; //两次按下不能短于 50ms
bool Button_Pressed_2 = false;
unsigned long LastPressTime = 0; // 记录上次按下的时间
unsigned long LastPressTime_2 = 0;
void IRAM_ATTR HandleButtonPress() { //ICACHE_RAM_ATTR函数强制存到RAM里
  return;
}


void setup() {
  Serial.begin(115200);
  ScreenInit();
  SPIFFS.begin();

  pinMode(BUTTON_PIN, INPUT_PULLUP);
  attachInterrupt(BUTTON_PIN, HandleButtonPress, FALLING);
  pinMode(BUTTON_PIN_2, INPUT_PULLUP);
  attachInterrupt(BUTTON_PIN_2, HandleButtonPress, RISING);
  StartWifiAP();
  Serial.println("HotSpot Started");
  Serial.println("HotSpot Addr: " + WiFi.softAPIP().toString());
  State = STATE_NOT_SET;
  LoadWifiConfig();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Locacl Ip: ");
    Serial.println(WiFi.localIP());  // 打印本机IP
    TimeClient.begin();
    TimeClient.update();
    State = STATE_WIFI_CONNECTED;
  }

  HTTPServerResponseConfig();
  
  delay(500);
  Moe();
  delay(500);
  ScreenClear();
  Dead();
  delay(500);
  ScreenClear();
  Pig();
  delay(500);
  ScreenClear();
  Emm();
  delay(500);
  ScreenClear();
  ShowWiFi(WiFi.softAPIP().toString(),WiFi.localIP().toString(),State);
  delay(2000);
  
}
int lastState;
void loop() {
  String inString="";
  while(Serial.available()>0){
    inString += char(Serial.read());
    delay(10);      // 延时函数用于等待字符完全进入缓冲区
  }
  HandleSerialMessage(inString);
  if(State == STATE_WIFI_CONNECTING) {
    Serial.println("WiFi connecting");
    unsigned long startAttempt = millis();
    while(WiFi.status() != WL_CONNECTED) { // wait for the Wi-Fi to connect
      Serial.print(".");
      delay(500);
      if(millis() - startAttempt > 5000) {
        State = STATE_WIFI_DISCONNECTED;
        break;
      }
    }
  } else if (WiFi.status() != WL_CONNECTED && State != STATE_NOT_SET) { //当wifi断开后，触发事件会尝试重连三次wifi，但这还不够，我们在这里让他一直尝试重连
    Serial.println("WiFi disconnected");
    State = STATE_WIFI_DISCONNECTED;
  }
  if (WiFi.status() == WL_CONNECTED && State != STATE_WIFI_CONNECTED) { //首次配置wifi后，以及断线重连后，需要更新屏幕内容以及状态
    Serial.println("WiFi Connected");
    State = STATE_WIFI_CONNECTED;
  }

  if (State != lastState)
  {
    ScreenClear();
    ShowWiFi(WiFi.softAPIP().toString(),WiFi.localIP().toString(),State);
  }
  lastState = State;

  if (State == STATE_WIFI_DISCONNECTED) {
    TryReconnectWifi();
  }
}